<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class ConditionKeyController extends Controller
{
    //关联试验条件标题
    public function conditionTitle(Request $request)
    {
        $id = $request->id; //a_std_tool_item_rel ID

        if ($request->isMethod('POST')) {
            $data = $request->only(['std_id', 'tool_id', 'item_id', 'key', 'unit']);
            $data['std_tool_item_rel_id'] = $id;
            // dd($data);
            try {
                //插入数据    insert 返回true 或 false
                $result = DB::table('a_condition_key')->insertGetId($data);
            } catch (\Throwable $e) {
                return '2';
            }
            //将排序字段更新为id
            DB::table('a_condition_key')->where('id', $result)->update(['sort' => $result]);

            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        } else {
            $data = DB::table('a_condition_key')->where('std_tool_item_rel_id', $id)->orderBy('sort')->get();

            $sql = "SELECT
                    A.id,
                    A.std_id,
                    A.tool_id,
                    A.testitem_id,
                    B.num,
                    C.name AS itemname,
                    D.name AS toolname
                FROM
                    a_std_tool_item_rel A
                LEFT JOIN a_standard B ON A.std_id = B.id
                LEFT JOIN a_testitem C ON A.testitem_id = C.id
                LEFT JOIN a_tool D ON A.tool_id = D.id
                WHERE
                    A.id = :id";

            $data_rel = DB::select($sql, ['id' => $id]); //参数绑定可以避免 SQL 注入攻击
            // dd($data_rel);
            $data_rel = $data_rel[0];
            $excel_pos = DB::table('a_excel_pos as a')
                    ->leftJoin('a_std_tool_rel as b','a.std_tool_rel_id','=','b.id')
                    ->where([
                        'b.std_id'  => $data_rel->std_id,
                        'b.tool_id'  => $data_rel->tool_id,
                    ])
                    ->select('a.id', 'a.name','a.is_default')
                    ->get();
            /*++++++++++++++++++ 默认模板位置初始化到表 start +++++++++++++++++++*/
                $in = [];
                foreach ($excel_pos as $item) {
                    if($item->is_default == 1 && DB::table('a_excel_pos_condition_key')->where('excel_pos_id',$item->id)->doesntExist()){
                        foreach ($data as $dataItem) {
                            $in[] = [
                                'excel_pos_id' => $item->id,
                                'condition_key_id' => $dataItem->id,
                                'pos_start' => $dataItem->pos_start,
                                'pos_end' => $dataItem->pos_end,
                            ];
                        }
                        break;
                    }
                }
                $in ? DB::table('a_excel_pos_condition_key')->insert($in) : '';
            /*++++++++++++++++++ 默认模板位置初始化到表 end +++++++++++++++++++*/
            return view('admin.conditionKey.conditionTitle', compact('data_rel', 'data', 'excel_pos'));
        }
    }

    //试验条件标题 删除
    public function del(Request $request)
    {
        $id = $request->input('id');
        try {
            // delete 返回受影响的行数
            $result = DB::table('a_condition_key')->where('id', $id)->delete();
        } catch (\Throwable $e) {
            return '2';
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ? '1' : '0';
    }

    /**
     * 排序 试验条件标题
     */
    public function saveSortConditionKey(Request $request)
    {
        $excel_pos_id = $request->excel_pos_id;
        $isDef = DB::table('a_excel_pos')->where('id',$excel_pos_id)->value('is_default');
        $updatas = request('data',[]);
        DB::beginTransaction();
        try{
            $in = [];
            foreach ($updatas as $id => $updata) {
                if ($isDef === 1) {
                    DB::table('a_condition_key')->where('id', $id)->update($updata);
                }
                $o_ep_tb = 'a_excel_pos_condition_key';
                $where = ['excel_pos_id'=>$excel_pos_id,'condition_key_id'=>$id];
                $up = ['pos_start'=>$updata['pos_start'],'pos_end'=>$updata['pos_end']];
                if (DB::table($o_ep_tb)->where($where)->exists()) {
                    DB::table($o_ep_tb)->where($where)->update($up);
                }else{
                    $in[] = array_merge($up,$where);
                }
            }
            DB::table($o_ep_tb)->insert($in);
            DB::commit();
        }catch(\Exception $exception){
            DB::rollBack();
            return "操作失败：".$exception->getMessage();
        }
        return 1;
    }
}
